let step = 1

function formatClassName(className) {
    return className.replaceAll(' ', '-')
}

var cy = cytoscape({
	container: $('#cy'),
	style: [ // the stylesheet for the graph
		{
			selector: 'node',
			style: {
				'background-color': '#666',
				'label': 'data(displayName)',
                'border-width': 4,
                'border-color': 'white'
			}
		},
        {
            selector: '.Reaction',
            style: {
                'background-color': 'red'
            }
        },
        {
            selector: '.Chemical-Compound',
            style: {
                'background-color': 'blue'
            }
        },
        {
            selector: '.Protein',
            style: {
                'background-color': 'yellow'
            }
        },
        {
            selector: '.Complex',
            style: {
                'background-color': 'black'
            }
        },
		{
			selector: 'edge',
			style: {
				'width': 3,
				'line-color': '#ccc',
				'target-arrow-color': '#ccc',
				'target-arrow-shape': 'triangle',
				'curve-style': 'bezier',
                'label': 'data(id)'
			}
		}
	]
})


function sort() {
	var layout = cy.layout({
		name: 'cose'
	})
	layout.run()
}

var app = new Vue({
    el: '#app',
    data: {
        id: '',
        ptQuery: {},
        ptEntity: [],
        uberonQuery: {},
        uberonGraph: {},
        uberonContinuousWithQuery: {}
    },
    methods: {
        updateID: function(id) {
            this.id = id
            console.log(`Updated ID to ${id}.`)
        },
        clean: function() {
            this.ptQuery = {}
            this.ptEntity = []
            this.uberonQuery = {}
            this.uberonGraph = {}
            this.uberonContinuousWithQuery = {}
        },
        matchSpecs: function(tab, index) {
            return tab.schemaClasses[index] != 'FailedReaction' & $('#starter-species').val() == tab.species[index]
        },
        matchUberonSpecs: function(edge) {
            return [
                'connects',
                'contributes to morphology of',
                'channels_from',
                'branching part of',
                'part of'
            ].indexOf(edge.label) != -1
        }
    },
    computed: {
        illustrate: function() {
            return this.uberonQuery._embedded.terms[0].annotation['depicted by']?.[0] || '#'
        }
    },
    watch: {
        id: function(newVal, oldVal) {
            this.clean()

            if ( newVal.startsWith('R-') ) {
                if ( newVal.startsWith('R-ALL-') ) {
                    $.get(`https://reactome.org/ContentService/data/entity/${newVal}/componentOf`, function(res) {
                        app.ptEntity = res
                    })
                }
    
                $.get(`https://reactome.org/ContentService/data/query/${newVal}`, function(res) {
                    app.ptQuery = res
                    $('#starter-species').val(app.ptQuery.speciesName || $('#starter-species').val())
                    compartmentName = (function () { return app.ptQuery.compartment?.[0].displayName || 'Unknown'})()
                    
                    if ( cy.$(`#${newVal}`).length == 0 ) {
                        if ( cy.$(`#${compartmentName.replaceAll(' ', '-')}`).length == 0 ) {
                            cy.add({
                                data: {
                                    id: compartmentName.replaceAll(' ', '-'),
                                    displayName: compartmentName
                                }
                            })
                        }
    
                        cy.add({
                            group: 'nodes',
                            data: {
                                id: newVal,
                                displayName: app.ptQuery.displayName,
                                parent: compartmentName.replaceAll(' ', '-')
                            },
                            classes: [formatClassName(app.ptQuery.className)]
                        })
                        // console.log(app.ptQuery.className)
                    }
    
                    // var time = new Date()
                
                    if ( oldVal != '' ) {
                        cy.add({
                            group: 'edges',
                            data: {
                                // id: `${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`,
                                id: step++,
                                source: oldVal,
                                target: newVal
                            }
                        })
                    }
                    sort()
                })
            }
            else if ( newVal.startsWith('UBERON_') ) {
                $.get(`https://www.ebi.ac.uk/ols/api/ontologies/uberon/terms?iri=http://purl.obolibrary.org/obo/${newVal}`, function(res) {
                    app.uberonQuery = res
                    continuous = res._embedded?.terms?.[0]._links.continuous_with || false

                    if ( continuous ) {
                        $.get(continuous.href, function(continuousRes) {
                            app.uberonContinuousWithQuery = continuousRes
                        })
                    }
                })

                $.get(`https://www.ebi.ac.uk/ols/api/ontologies/uberon/terms/http%253A%252F%252Fpurl.obolibrary.org%252Fobo%252F${newVal}/graph`, function(res) {
                    app.uberonGraph = res
                })
            }
        }
    }
})

document.onkeyup = function(event) {
    var e = event || window.event;
    if ( e && e.keyCode == 13 ) {
        initGame()
    }
}

function initGame() {
    app.id = $('#starter-ID').attr('placeholder')
}
